package top.cdmrx.demo.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import top.cdmrx.demo.edu.entity.Subject;
import top.cdmrx.demo.edu.entity.excel.SubjectData;
import top.cdmrx.demo.edu.service.SubjectService;

import java.util.Map;

/**
 * Created by Mr.陈 time on 2021/9/14 | 13:16
 **/
@Component
public class SubjectEventListener extends AnalysisEventListener<SubjectData> {

    @Autowired
    private  SubjectService subjectService;

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData==null){
            throw  new RuntimeException("该文件数据为空！");
        }


        //判断一级分类是否重复,进行添加处理
        String oneSubjectTitle=subjectData.getOneSubjectName();
        System.out.println(subjectService);
        System.out.println(this);
        Subject subject = this.existOneSubject(subjectService,oneSubjectTitle);

        if (subject==null){ //没有相同的一级分类。进行添加
            subject=new Subject();
            subject.setParentId("0");
            subject.setTitle(oneSubjectTitle);  //一级分类名称

            subjectService.save(subject);
        }

        //二级分类进行添加和判断重复
        //获取一级分类的id值,用于填充parent_id
        String pid=subject.getId();

        //判断二级分类是否重复
        Subject subject2 = this.
                existTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);

        if (subject2==null){
            subject2=new Subject();
            subject2.setParentId(pid);
            subject2.setTitle(subjectData.getTwoSubjectName());  //一级分类名称

            subjectService.save(subject2);
        }

    }


    //判断一级分类不可重复添加
    private Subject existOneSubject(SubjectService subjectService,String name){
        QueryWrapper<Subject> subjectQueryWrapper = new QueryWrapper<>();

        subjectQueryWrapper.eq("title",name);
        subjectQueryWrapper.eq("parent_id","0");

        Subject one = subjectService.getOne(subjectQueryWrapper);

        return one;
    }

    //判断二级分类不可重复添加
    private Subject existTwoSubject(SubjectService subjectService,String name,String pid){
        QueryWrapper<Subject> subjectQueryWrapper = new QueryWrapper<>();

        subjectQueryWrapper.eq("title",name);
        subjectQueryWrapper.eq("parent_id",pid);

        Subject one = subjectService.getOne(subjectQueryWrapper);

        return one;
    }


    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
